#import "DataType.h"
#import "IAPManager.h"
#import "DevourerAppDelegate.h"
#import "DataSL.h"

@implementation IAPManager

static const NSString* sIapIds[IAP_COUNT] = {
	@"com.ambielgemini.devourer.01",
	@"com.ambielgemini.devourer.02",
	@"com.ambielgemini.devourer.03",
	@"com.ambielgemini.devourer.04",
	@"com.ambielgemini.devourer.05",
	@"com.ambielgemini.devourer.06",
	@"com.ambielgemini.devourer.07",
};

static IAPManager* _sharedManager = NULL;

#pragma mark -
#pragma mark Initialize

+(IAPManager*)sharedManager
{
	if(!_sharedManager)
		_sharedManager = [[IAPManager alloc] init];
	return _sharedManager;
}

-(id)init
{
	if((self = [super init])) {
		mConnected = false;
		[[SKPaymentQueue defaultQueue] addTransactionObserver:self];
		[self requestProductData];
	}
	return self;
}

-(void)dealloc
{
	[_sharedManager release];
	[super dealloc];
}

#pragma mark -
#pragma mark 购买相关函数

// 购买请求
-(void)requestPurchase:(int)iapId
{
	if([SKPaymentQueue canMakePayments]) {
		SKPayment* payment = [SKPayment paymentWithProductIdentifier:sIapIds[iapId]];
		[[SKPaymentQueue defaultQueue] addPayment:payment];
	} else {
		UIAlertView* alert = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"PurchaseFailed",nil)
														message:NSLocalizedString(@"PurchaseClosedMsg",nil)
													   delegate:self
											  cancelButtonTitle:@"OK"
											  otherButtonTitles:nil];
		gWaitingIAP = false;
		DevourerAppDelegate* app = [[UIApplication sharedApplication] delegate];
		[app.activityView stopAnimating];
		[alert show];
		[alert release];
	}
}

// 购买成功处理
-(void)provideContent:(NSString*)productId
{
	for(int i=0; i<IAP_COUNT; i++) {
		if([productId isEqualToString:sIapIds[i]]) {
			[[SimpleAudioEngine sharedEngine] playEffect:EF_COIN];
			gGlobalData.gold += gIapGold[i];
		}
	}
	gSaveData();
}

#pragma mark -
#pragma mark SKPaymentTransactionObserver methods

-(void)paymentQueue:(SKPaymentQueue*)queue updatedTransactions:(NSArray*)transactions
{
	DevourerAppDelegate* app;
	for(SKPaymentTransaction* transaction in transactions) {
//		NSLog(@"Transaction state:%d", transaction.transactionState);
		switch (transaction.transactionState) {
			case SKPaymentTransactionStatePurchased:
				[self provideContent:transaction.payment.productIdentifier];
				[[SKPaymentQueue defaultQueue] finishTransaction:transaction];	
				app = [[UIApplication sharedApplication] delegate];
				[app.activityView stopAnimating];
				gWaitingIAP = false;
				break;
			case SKPaymentTransactionStateFailed:
				if(transaction.error.code != SKErrorPaymentCancelled) {
//					NSLog(@"IAP Failed. Code:%d", transaction.error.code);
					UIAlertView* alert = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"PurchaseFailed",nil)
																	message:NSLocalizedString(@"PurchaseFailedMsg",nil)
																   delegate:self
														  cancelButtonTitle:@"OK"
														  otherButtonTitles: nil];
					[alert show];
					[alert release];
				}
				[[SKPaymentQueue defaultQueue] finishTransaction:transaction];	
				app = [[UIApplication sharedApplication] delegate];
				[app.activityView stopAnimating];
				gWaitingIAP = false;
				break;
			case SKPaymentTransactionStateRestored:
				[self provideContent:transaction.originalTransaction.payment.productIdentifier];
				[[SKPaymentQueue defaultQueue] finishTransaction:transaction];	
				break;
		}
	}
}

#pragma mark -
#pragma mark SKProductsRequestDelegate methods

-(void)requestProductData
{
	SKProductsRequest* request= [[SKProductsRequest alloc] initWithProductIdentifiers:[NSSet setWithObjects:sIapIds count:7]];
	request.delegate = self;
	[request start];
}

#pragma mark SKProductsRequestDelegate methods

-(void)productsRequest:(SKProductsRequest*)request didReceiveResponse:(SKProductsResponse*)response
{
//	NSLog(@"IAP Get all items - Count:%d", [response.products count]);
//	NSLog(@"IAP Get all items - Invalid Count:%d", [response.invalidProductIdentifiers count]);
//	for(SKProduct* product in response.products) {
//		NSLog(@"  IAP Item: %@, Cost: %f, ID: %@",product.localizedTitle,[product.price doubleValue],product.productIdentifier);
//	}
	[request release];
}

@end
